import { getUserInfo } from '@/api/user'
import router from '@/router'

const state = {
  usertoken: localStorage.getItem('usertoken') || '',
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.usertoken = token
    localStorage.setItem('usertoken', token)
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  }

}

const actions = {
  async loginAction(ctx, data) {
    ctx.commit('setToken', data)
    router.push('/dashboard')
  },
  async getUserInfo(ctx) {
    const res = await getUserInfo()
    // todo: 处理用户信息
    ctx.commit('setUserInfo', res)
    //  返回用户信息
    return res
  },
  // 封装退出登录action
  logoutAction(ctx) {
    ctx.commit('setToken', '')
    // removeToken()
    ctx.commit('setUserInfo', {})
    router.push('/login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

